package com.atyjh.reggie.controller;

import com.atyjh.reggie.dto.Result;
import com.atyjh.reggie.entity.Category;
import com.atyjh.reggie.service.ICategoryService;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.util.List;

/**
 * @author yjh
 * @since jdk1.8.0_311 2022.06.16
 */
@RestController
@RequestMapping("/category")
@Slf4j
public class CategoryController {

    @Autowired
    private ICategoryService categoryService;

    @PostMapping
    public Result<String> save(@RequestBody Category category) {
        if (categoryService.save(category)) {
            return Result.success("添加成功！");
        }
        return Result.error("添加失败！请重新添加");
    }

    @GetMapping("/page")
    public Result<Page<Category>> page(@RequestParam("page")Integer page,
                                       @RequestParam("pageSize")Integer pageSize){

        return categoryService.pageDish(page, pageSize);

    }

    @PutMapping
    public Result<String> update(@RequestBody Category category) {
        if (categoryService.updateById(category)) {
            return Result.success("修改成功！");
        }
        return Result.error("修改失败！请重新修改");
    }

    @DeleteMapping
    public Result<String> delete(@RequestParam("ids") Long id) {
        return categoryService.delete(id);
    }


    @GetMapping("/list")
    public Result<List<Category>> list(@RequestParam(value = "type", required = false)Integer type) {
        LambdaQueryWrapper<Category> lqw = new LambdaQueryWrapper<Category>()
                .eq(type != null, Category::getType, type)
                .orderByAsc(Category::getSort)
                .orderByDesc(Category::getUpdateTime);
        return Result.success(categoryService.list(lqw));
    }

}
